home *** CD-ROM | disk | FTP | other *** search
- Path: solon.com!not-for-mail
- From: kanze@gabi-soft.fr (J. Kanze)
- Newsgroups: comp.lang.c.moderated,comp.lang.c
- Subject: Re: Please help me elect rounding of int division
- Date: 22 Feb 1996 18:05:21 -0600
- Organization: GABI Software, Sarl.
- Sender: clc@solutions.solon.com
- Approved: clc@solutions.solon.com
- Message-ID: <4gj0c1$li1@solutions.solon.com>
- References: <4gfaif$1tt@solutions.solon.com> <4ggbm9$85t@solutions.solon.com>
- NNTP-Posting-Host: solutions.solon.com
-
- In article <4ggbm9$85t@solutions.solon.com> Gihan Perera
- <Gihan@andante.demon.co.uk> writes:
-
- |> In article <4gfaif$1tt@solutions.solon.com>
- |> swedecj@vcnet.com "Carl Jacobson" writes:
-
- |> > Please help me solve this task.
- |> >
- |> > I have now tried (Borland C++ version 3.0) for two solid days to write
- |> > a function that would allow me to round the quotient of (a/b) up or
- |> > down based on the "nearest" integer instead of being truncated to the
- |> > smallest. If exactly half way, return the "odd."
-
- |> The first part is easy. If you're using reals, add 0.5 to (a/b) before
- |> truncating it. If you're doing the whole thing with integers, use:
-
- |> q = ( a + b/2 ) / b;
-
- |> which has the same effect.
-
- |> But neither of these meets your second criterion ("return the odd") -
- |> they both round _up_ if exactly half-way. Sorry - I don't know any
- |> easy trick for that.
-
- Both also fail when the results are negative. For integer arithmetic
- involving only non-negative values, the following expression should do
- the trick:
-
- (a + b/2) / b - (b % 2 == 0 && a % b == b/2 && ((a/b) & 1) == 0)
-
- To handle values no matter what sign, the only solution I can think of
- off hand is brute force:
-
- (a >= 0)
- ? ((b >= 0)
- ? (a + b/2) / b
- - (b % 2 == 0 && a % b == b/2 && ((a/b) & 1) == 0)
- : -((a + -b/2) / -b
- - (-b % 2 == 0 && a % -b == -b/2 && ((a/-b) & 1) == 0))
- )
- : ((b >= 0)
- ? -((-a + b/2) / b
- - (b % 2 == 0 && -a % b == b/2 && ((-a/b) & 1) == 0))
- : (-a + -b/2) / -b
- - (-b % 2 == 0 && -a % -b == -b/2 && ((-a/-b) & 1) == 0)
- )
-
- In production code, this may be pushing the expressive power of
- expressions a little too much for legibility:-).
-
- The above is all off the top of my head. No guarantee. (And it
- obviously doesn't work if b == 0. But then, what does?)
- --
- James Kanze (+33) 88 14 49 00 email: kanze@gabi-soft.fr
- GABI Software, Sarl., 8 rue des Francs Bourgeois, 67000 Strasbourg, France
- Conseils, Θtudes et rΘalisations en logiciel orientΘ objet --
- -- A la recherche d'une activitΘ dans une region francophone
-